package com.zhl.study.controller;

import com.zhl.study.service.BcmpFileInfoService;
import com.zhl.study.base.ResponseFactory;
import com.zhl.study.base.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description SpringBoot 实现 MySQL 百万级数据量导出并避免 OOM 的解决方案  比较stream流读取与传统方案对内存占用的大小
 * @Author: z156940l@outlook.com
 * @className HelloController
 * @Date: 2023/3/21 23:48
 */
@RestController
@RequestMapping("download")
@Slf4j
@Api(value = "百万级数据量", tags = "百万级数据量")
public class HelloController {
    private final BcmpFileInfoService authorsService;

    public HelloController(BcmpFileInfoService authorsService) {
        this.authorsService = authorsService;
    }

    @GetMapping("streamDownload")
    @ApiOperation(httpMethod = "GET", value = "数据流导出，堆内存占用小避免oom")
    public Result<Void> streamDownload(HttpServletResponse response)
            throws IOException {
        long start = System.currentTimeMillis();
        authorsService.streamDownload(response);
        log.info("streamDownload耗时：{}",(System.currentTimeMillis()-start));
        return ResponseFactory.ok();
    }

    @GetMapping("traditionDownload")
    @ApiOperation(httpMethod = "GET", value = "传统导出，查到内存再做导出，oom风险极大")
    public Result<Void> traditionDownload(HttpServletResponse response)
            throws IOException {
        long start = System.currentTimeMillis();
        authorsService.traditionDownload(response);
        log.info("traditionDownload耗时：{}",(System.currentTimeMillis()-start));
        return ResponseFactory.ok();
    }



}
